<?php
namespace app\Capital\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Model;
use think\Db;
use app\Capital\model\capital as CapitalModel;
use app\Capital\model\account;
class Withdrawals extends Admin{
    public function index(){
        $map = $this->getMap();
        $status = input('status');
        if (99 == $status) {
            $map['status'] = 0;
        }
        $map['user_type'] = 1;
        $list_tab = [
            'tab1' => ['title' => '会员提现列表', 'url' => url('index')],
            'tab2' => ['title' => '店铺提现列表', 'url' => url('shop_withdrawals')],
        ];
        $data = Db::name("withdrawals")->where($map)->order("id desc")->select();
        return ZBuilder::make('table')
            ->setTabNav($list_tab, 'tab1')
            ->hideCheckbox()
            ->setSearch(['id' => '单据ID', 'no' => '单据号', 'name' => '用户名称'])
            ->addColumns([
                ['no', '单据号'],
                ['name', '会员名称'],
                ['num', '提现金额', 'callback', 'getPrice'],
                ['type', '提现原因', 'type', '', CapitalModel::get_type(6)],
                ['createtime', '创建时间', 'datetime'],
            ])
            ->addColumn('status', '状态', 'status', '', [0 => '待审核', 1 => '已审核', 2 => '已作废'])
            ->addColumn('right_button', '操作', 'btn')
            ->addTopButton('add', ['title' => '新增', 'table' => '', 'href' => url('member_withdrawals_add')])
            ->addTopButton('custom', ['title' => '待审核', 'icon' => 'fa fa-fw fa-cogs', 'href' => url('index', ['status' => 99])])
            ->addRightButton('custom', ['title' => '修改单据', 'icon' => 'fa fa-wrench','href'=>url('withdrawals_edit',['id'=>'__id__'])])// 批量添加右侧按钮
            ->addRightButton('custom', ['title' => '查看单据', 'icon' => 'fa fa-fw fa-eye','href'=>url('withdrawals_see',['id'=>'__id__','user_type'=>1])])// 批量添加右侧按钮
            ->addRightButton('custom', ['title' => '单据审核', 'icon' => 'fa fa-fw fa-question-circle','href'=>url('member_examine',['id'=>'__id__'])])// 批量添加右侧按钮
            ->addTimeFilter('createtime')
            ->setRowList($data)
            ->fetch();
    }

    //店铺提现
    public function shop_withdrawals(){
        $map = $this->getMap();
        $status = input('status');
        if (99 == $status) {
            $map['status'] = 0;
        }
        $map['user_type'] = 2;
        $list_tab = [
            'tab1' => ['title' => '会员提现列表', 'url' => url('index')],
            'tab2' => ['title' => '店铺提现列表', 'url' => url('shop_withdrawals')],
        ];
        $data = Db::name("withdrawals")->where($map)->order("id desc")->select();
        return ZBuilder::make('table')
            ->setTabNav($list_tab, 'tab2')
            ->hideCheckbox()
            ->setSearch(['id' => '单据ID', 'no' => '单据号', 'name' => '用户名称'])
            ->addColumns([
                ['no', '单据号'],
                ['name', '店铺名称'],
                ['num', '提现金额', 'callback', 'getPrice'],
                ['type', '提现原因', 'type', '', CapitalModel::get_type(6)],
                ['createtime', '创建时间', 'datetime'],
            ])
            ->addColumn('status', '状态', 'status', '', [0 => '待审核', 1 => '已审核', 2 => '已作废'])
            ->addColumn('right_button', '操作', 'btn')
            ->addTopButton('add', ['title' => '新增', 'table' => '', 'href' => url('shop_withdrawals_add')])
            ->addTopButton('custom', ['title' => '待审核', 'icon' => 'fa fa-fw fa-cogs', 'href' => url('shop_withdrawals', ['status' => 99])])
            ->addRightButton('custom', ['title' => '修改单据', 'icon' => 'fa fa-wrench','href'=>url('withdrawals_edit',['id'=>'__id__'])])// 批量添加右侧按钮
            ->addRightButton('custom', ['title' => '查看单据', 'icon' => 'fa fa-fw fa-eye','href'=>url('withdrawals_see',['id'=>'__id__','user_type'=>2])])// 批量添加右侧按钮
            ->addRightButton('custom', ['title' => '单据审核', 'icon' => 'fa fa-fw fa-question-circle','href'=>url('shop_examine',['id'=>'__id__'])])// 批量添加右侧按钮
            ->addTimeFilter('createtime')
            ->setRowList($data)
            ->fetch();
    }

    //新增会员提现
    public function member_withdrawals_add(){
        return ZBuilder::make('form')
            ->setPageTitle('新建会员提现申请')
            ->addSelect('userid','会员','','','','ajax','',['url'=>'/admin.php/Capital/adjustment/adjustment_list/type/1','datakey'=>'id','dataname'=>'name'])
            ->addText('num', '提现金额', '', '', '', 'onkeyup="if(isNaN(value))execCommand(\'undo\')" onafterpaste="if(isNaN(value))execCommand(\'undo\')"', '')
            ->addSelect('type', '提现原因', '', CapitalModel::get_type(6))
            ->addTextarea('notes','备注')
            ->layout(['userid' => 4, 'num' => 4, 'type' => 4])
            ->setUrl(url('withdrawals_save',['user_type'=>1]))
            ->fetch();
    }

    //店铺提现新增
    public function shop_withdrawals_add(){
        return ZBuilder::make('form')
            ->setPageTitle('新建店铺提现申请')
            ->addSelect('userid','店铺','','','','ajax','',['url'=>'/admin.php/Capital/adjustment/adjustment_list/type/2','datakey'=>'id','dataname'=>'name'])
            ->addText('num', '提现金额', '', '', '', 'onkeyup="if(isNaN(value))execCommand(\'undo\')" onafterpaste="if(isNaN(value))execCommand(\'undo\')"', '')
            ->addSelect('type', '提现原因', '', CapitalModel::get_type(6))
            ->addTextarea('notes','备注')
            ->layout(['userid' => 4, 'num' => 4, 'type' => 4])
            ->setUrl(url('withdrawals_save',['user_type'=>2]))
            ->fetch();

    }

    //提现申请保存
    public function withdrawals_save(){
        $data = input();
        if ($data) {
            $user = $data['userid'][0];
            if (0 == $data['type']) {
                return $this->error("请选择提现单原因");
            } else {
                if ($user) {
                    $userArr = explode('-', $user);
                    $data['name'] = $userArr[1];
                    $data['userid'] = $userArr[0];
                    if (1 == $data['user_type']) {
                        //获取会员对应银行账户信息
                        $bank = Db::name("member_settlement")->where("memberid", $data['userid'])->find();
                        $data['bank_msgid'] = $bank['id'] ? $bank['id'] : '';
                        $url = "index";
                    } elseif (2 == $data['user_type']) {
                        $data['bank_msgid'] = 2;
                        $url = "shop_withdrawals";
                    }
                    $No = date('YmdHis');
                    $data['createtime'] = time();
                    $data['num'] = setPrice($data['num']);
                    $data['no'] = 'TX-' . $data['userid'] . $No;
                    $result = Db::name("withdrawals")->insert($data);
                    if ($result) {
                        return $this->success("新增提现申请单成功", url($url));
                    } else {
                        return $this->error("新增提现申请单失败");
                    }
                } else {
                    return $this->error("新增提现申请单失败");
                }
                return $this->error("新增提现申请单失败");
            }
        }
    }
        //提现单据修改
        public function withdrawals_edit(){
            $id=input("id");
            $withdrawals=Db::name("withdrawals")->where("id",$id)->find();
            if(0!=$withdrawals['status']){
                $this->error("已审核订单不能修改");
            }
            $withdrawals['num']=getPrice($withdrawals['num']);
            if(1==$withdrawals['user_type']){
                $user="会员";
            }else{
                $user="店铺";
            }
            return ZBuilder::make('form')
                ->setPageTitle($user.'提现申请单')
                ->addHidden('id','单据ID')
                ->addHidden('userid',$user.'ID')
                ->addStatic('no', '单号')
                ->addStatic('name', $user.'名称')
                ->addText('num', '提现金额','','','','onkeyup="if(isNaN(value))execCommand(\'undo\')" 6onafterpaste="if(isNaN(value))execCommand(\'undo\')"')
                ->addSelect('type', '提现原因', '', CapitalModel::get_type(6),$withdrawals['type'])
                ->addTextarea('notes','备注')
                ->layout(['no'=>2,'name'=>2,'num'=>2,'type'=>3])
                ->setFormData($withdrawals)
                ->setUrl(url('save_withdrawals_edit'))
                ->fetch();
        }

    //会员提现单据审核
    public function member_examine(){
        $id=input('id');
        if($id){
                $withdrawals=Db::name('withdrawals')->where('id',$id)->find();
                if($withdrawals){
                    $member=Db::name('member')->where('id',$withdrawals['userid'])->find();
                    if($member){
                        Db::startTrans();
                        try{
                            $re=Db::name('withdrawals')->where('id',$id)->setField('status',1);
                         //   dump($re);exit();
                            if($re){
                                $num=$member['balance']-$withdrawals['num'];
                                $result=Db::name('member')->where('id',$withdrawals['userid'])->setField('balance',$num);
                                if($result){
                                    $data['no']=$withdrawals['no'];
                                    $data['memberid']=$withdrawals['userid'];
                                    $data['num']=$withdrawals['num'];
                                    $data['balance']=$member['balance'];
                                    $data['type']=3;
                                    $account=account::add_member_account($data);
                                    if($account){
                                        $msg="单据审核成功，会员账户余额已更新，账户变动数据已保存";
                                    }
                                }
                            }else{
                                $this->error("单据无需重复审核");
                            }
                            // 提交事务
                            Db::commit();
                        }catch (\Exception $e) {
                            // 回滚事务
                            Db::rollback();
                            $this->error('单据审核失败');
                        }
                        $this->success($msg);
                    }else{
                        $this->error('未找到对应提现单据');
                    }
                }else{
                    $this->error("单据单据错误");
                }
        }else{
            $this->error('提现单据错误');
        }
    }

    //店铺提现单据审核
    public function shop_examine(){
        $id=input('id');
        if($id){
            $withdrawals=Db::name('withdrawals')->where('id',$id)->find();
            if($withdrawals){
                $shop=Db::name('shop')->where('id',$withdrawals['userid'])->find();
                if($shop){
                    Db::startTrans();
                    try{
                        $re=Db::name('withdrawals')->where('id',$id)->setField('status',1);
                        //   dump($re);exit();
                        if($re){
                            $num=$shop['balance']-$withdrawals['num'];
                            $result=Db::name('shop')->where('id',$withdrawals['userid'])->setField('balance',$num);
                            if($result){
                                $data['no']=$withdrawals['no'];
                                $data['shopid']=$withdrawals['userid'];
                                $data['num']=$withdrawals['num'];
                                $data['balance']=$shop['balance'];
                                $data['type']=3;
                                $account=account::add_shop_account($data);
                                if($account){
                                    $msg="单据审核成功，店铺账户余额已更新，账户变动数据已保存";
                                }
                            }
                        }else{
                            $this->error("单据无需重复审核");
                        }
                        // 提交事务
                        Db::commit();
                    }catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        $this->error('单据审核失败');
                    }
                    $this->success($msg);
                }else{
                    $this->error('未找到对应单据的店铺');
                }
            }else{
                $this->error("单据不存在");
            }
        }else{
            $this->error('提现单据错误');
        }
    }
    //提现单据修改保存
    public function save_withdrawals_edit(){
        $data=input();
        if($data['id']){
            $withdrawals=Db::name('withdrawals')->where('id',$data['id'])->find();
            if($withdrawals){
                if(0==$withdrawals['status']){
                    $result=Db::name('withdrawals')->where('id',$data['id'])->update($data);
                    if($result){
                        $url=$withdrawals['user_type']==1 ? 'index' :"shop_withdrawals";
                        $this->success("单据修改成功",url($url));
                    }else{
                        $this->error("单据修改错误");
                    }
                }else{
                    $this->error("已审核单据不能修改");
                }
            }else{
                $this->error("单据未找到");
            }
        }else{
            $this->error("单据错误");
        }
    }
    //单据查看
    public function withdrawals_see(){
        $id=input('id');
        $user_type=input('user_type');
        if($id){
            $withdrawals=Db::name("withdrawals")->where('id',$id)->find();
            if($withdrawals){
                $withdrawals['num']=getPrice($withdrawals['num']);
                $type=CapitalModel::get_type(6);
                $withdrawals['type']=$type[$withdrawals['type']];
                if(1==$user_type){
                    $user="会员";
                    $bank=Db::name("member_settlement")->field('bankno,bankname')->where('memberid',$withdrawals['userid'])->find();
                }else{
                    $user="店铺";
                    $shop=Db::name("shop")->where("id",$withdrawals['userid'])->find();
                    $bank=Db::name("member_settlement")->field('bankno,bankname')->where('memberid',$shop['memberid'])->find();
                }
                if($bank){
                    $withdrawals=array_merge($withdrawals,$bank);
                }
                return ZBuilder::make('form')
                    ->setPageTitle('提现单据详情')
                    ->addStatic('no', '单号')
                    ->addStatic('name', $user.'名称')
                    ->addStatic('num', '提现金额')
                    ->addStatic('bankno', '银行账号')
                    ->addStatic('bankname', '开户行')
                    ->addStatic('type', '提现原因')
                    ->addStatic('notes','备注')
                    ->layout(['no'=>4,'name'=>4,'num'=>4,'type'=>4,'bankno'=>4,'bankname'=>4])
                    ->setFormData($withdrawals)
                    ->hideBtn('submit,back')
                    ->fetch();
            }else{
                $this->error("单据错误");
            }
        }else{
            $this->error("单据ID错误");
        }
    }

}